/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 6/25/18
Time: 12:54 PM
 */

package Cn.Sarkar.MMS.LayerOne.Repositories.RDBMSRepositories

import Cn.Sarkar.Entities.Common.Additional.IName
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.QueryBuilderExtensions.SelectQueryExpression.and
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.QueryBuilderExtensions.SelectQueryExpression.equals
import Cn.Sarkar.EntityDream.CoreEngine.RDBMS.Core.QueryBuilderExtensions.SelectQueryExpression.singleOrNull
import Cn.Sarkar.MMS.DataBaseDefinations.Additional.Names
import Cn.Sarkar.MMS.Entities.Additional.Name
import Cn.Sarkar.MMS.Entities.DataSources.IDataSource
import Cn.Sarkar.MMS.LayerOne.Repositories.Interfaces.INameRepository
import Cn.Sarkar.MMS.LayerOne.Repositories.Interfaces.RepositoryResult
import Cn.Sarkar.MMS.LayerOne.Repositories.Interfaces.tryExecute

class NameRepository : INameRepository, IRDBMSRepositories {
    override fun getOrStore(_name: IName): RepositoryResult<IName?> = tryExecute {
        IDataSource.openAndAutoClose {db ->
            var name = db.names.singleOrNull {
                Names.Category equals _name.category and
                        (Names.Ug equals _name.ug) and
                        (Names.En equals _name.en) and
                        (Names.Zh equals _name.zh) and
                        (Names.Kz equals _name.kz) and
                        (Names.Ru equals _name.ru)

            }
            if (name == null) {
                name = Name(db).apply {
                    category = _name.category
                    ug = _name.ug
                    en = _name.en
                    zh = _name.zh
                    kz = _name.kz
                    ru = _name.ru
                }
                db.names.add(name)
                db.saveChanges()
            }
            name
        }
    }
}